<!-- 课程管理(模块) => 课程列表(菜单) => 页面 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('course.fields.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('common.inputTextPlaceholder') + t('course.fields.name')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('course.fields.teacher')" prop="teacher">
        <el-input
          v-model="queryParams.teacher"
          :placeholder="t('common.inputTextPlaceholder') + t('course.fields.teacher')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('course.fields.semesterId')" prop="semesterId">
        <el-select
          v-model="queryParams.semesterId"
          :placeholder="t('common.selectTextPlaceholder') + t('course.fields.semesterId')"
          clearable
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option
            v-for="item in semesterList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button type="success" plain @click="handleSyncData">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('course.sync.button') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iCourse-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('course.fields.semesterId')"
        field="semesterName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('course.fields.name')"
        field="name"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('course.fields.code')"
        field="code"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('course.fields.teacher')"
        field="teacher"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('course.fields.studentAmount')"
        field="studentAmount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('course.fields.missTwiceAmount')"
        field="missTwiceAmount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag
            class="cursor-pointer"
            v-if="scope.row.missTwiceAmount > 0"
            type="danger"
            @click="handleViewTwice(scope.row.missSign, 'course.index.missTitle')"
          >
            {{ scope.row.missTwiceAmount }}
          </el-tag>
          <el-tag v-else type="success">
            {{ scope.row.missTwiceAmount }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('course.fields.lateTwiceAmount')"
        field="lateTwiceAmount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag
            class="cursor-pointer"
            v-if="scope.row.lateTwiceAmount > 0"
            type="danger"
            @click="handleViewTwice(scope.row.beLate, 'course.index.lateTitle')"
          >
            {{ scope.row.lateTwiceAmount }}
          </el-tag>
          <el-tag v-else type="success">
            {{ scope.row.lateTwiceAmount }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('course.fields.earlyTwiceAmount')"
        field="earlyTwiceAmount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag
            class="cursor-pointer"
            v-if="scope.row.earlyTwiceAmount > 0"
            type="danger"
            @click="handleViewTwice(scope.row.leaveEarly, 'course.index.earlyTitle')"
          >
            {{ scope.row.earlyTwiceAmount }}
          </el-tag>
          <el-tag v-else type="success">
            {{ scope.row.earlyTwiceAmount }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="250"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleSelectTeacher(scope.row)"
            v-hasPermi="['course:course:admin']"
          >
            {{ t('course.index.operate.changeCourseTeacher') }}
          </el-button>
          <el-button link type="primary" @click="handleViewLog(scope.row.id)">
            {{ t('course.index.operate.signLog') }}
          </el-button>
          <el-button link type="primary" @click="handleExportLog(scope.row)">
            {{ t('course.index.operate.exportLog') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSelectAssistant(scope.row)"
            v-hasPermi="['course:course:assistantManage']"
          >
            {{ t('course.index.operate.assistantManage') }}
          </el-button>
          <el-button link type="primary" @click="handleViewStudent(scope.row)">
            {{ t('course.index.operate.studentList') }}
          </el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['course:course:sign']"
            @click="toggleStartClass(scope.row)"
          >
            {{
              scope.row.needClass
                ? t('course.index.operate.classBegin')
                : t('course.index.operate.classEnd')
            }}
          </el-button>
          <el-button
            v-if="scope.row.signLogId"
            link
            type="primary"
            @click="handleGenQr(scope.row)"
            v-hasPermi="['course:course:sign']"
          >
            {{
              !scope.row.needClass
                ? t('course.index.operate.checkInQrcode')
                : t('course.index.operate.checkOutQrcode')
            }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CourseForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="课程"
    upload-url="/course/course/import"
    template-url="/course/course/get-import-template"
    @success="getList"
  />

  <CourseTeacherSelect ref="courseTeacherSelectRef" @choose="getList" />
  <CourseAssistantView ref="courseAssistantViewRef" />
  <CourseStudentList ref="courseStudentListRef" />
  <GenQR ref="genQrRef" />

  <Dialog :title="t(accountTitle)" v-model="dialogVisible" width="700">
    <!-- 列表 -->
    <ContentWrap>
      <vxe-table
        id="miss-account-table"
        v-loading="accountLoading"
        :data="accountList"
        stripe
        :custom-config="vxeTableConfig"
        :column-config="{ resizable: true }"
        :size="vxeTableSize"
      >
        <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
        <vxe-column
          :title="t('signStudentLog.fields.studentName')"
          field="studentName"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('signStudentLog.fields.studentCode')"
          field="studentCode"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('signStudentLog.fields.studentPhone')"
          field="studentPhone"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
      </vxe-table>
    </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { CourseAdminRespVO, CourseApi } from '@/api/course/course'
import CourseForm from './CourseForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { SemesterApi, SemesterSimpleRespVO } from '@/api/course/semester'
import CourseTeacherSelect from '@/views/course/course/components/CourseTeacherSelect.vue'
import { SignLogApi } from '@/api/course/signlog'
import CourseAssistantView from '@/views/course/course/components/CourseAssistantView.vue'
import CourseStudentList from '@/views/course/course/components/CourseStudentList.vue'
import GenQR from '@/views/course/course/components/GenQR.vue'
import { CourseSignStudentLogListRespVO } from '@/api/course/signstudentlog'

/** 课程 列表 */
defineOptions({ name: 'Course' })

const router = useRouter() // 路由对象
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<CourseAdminRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  semesterId: undefined,
  code: undefined,
  teacher: undefined,
  teacherId: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CourseApi.getCoursePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof CourseForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CourseApi.deleteCourse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CourseApi.exportCourse(queryParams)
    download.excel(data, '课程.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 选择任课教师弹窗
const courseTeacherSelectRef = ref<InstanceType<typeof CourseTeacherSelect>>()
const handleSelectTeacher = (row: CourseAdminRespVO) => {
  courseTeacherSelectRef.value?.open(row)
}

// 查看签到记录
const handleViewLog = (courseId: number) => {
  router.push(`/course/sign-log/${courseId}`)
}

// 导出签到记录
const handleExportLog = async (row: CourseAdminRespVO) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loading.value = true
    const data = await SignLogApi.exportSignLog({ courseId: row.id })
    download.excel(data, `${row.name}-${row.code}-课程签到.xlsx`)
  } catch {
  } finally {
    loading.value = false
  }
}

// 课代表管理
const courseAssistantViewRef = ref<InstanceType<typeof CourseAssistantView>>()
const handleSelectAssistant = (row: CourseAdminRespVO) => {
  courseAssistantViewRef.value?.open(row)
}

// 学生列表
const courseStudentListRef = ref<InstanceType<typeof CourseStudentList>>()
const handleViewStudent = (row: CourseAdminRespVO) => {
  courseStudentListRef.value?.open(row)
}

const toggleStartClass = (row: CourseAdminRespVO) => {
  if (!row.needClass && !row.signLogId) {
    return
  }
  const data = {
    id: row.needClass ? undefined : row.signLogId,
    courseId: row.id,
    isClass: row.needClass
  }
  SignLogApi.createSignLog(data).then(() => getList())
}

// 生成二维码
const genQrRef = ref<InstanceType<typeof GenQR>>()
const handleGenQr = (row: CourseAdminRespVO) => {
  genQrRef.value?.open(row)
}

// 同步数据
const handleSyncData = async () => {
  try {
    await message.confirm(t('course.sync.syncTip'))
    // 发起导出
    loading.value = true
    const response = await CourseApi.syncNow()
    if (response) {
      message.success(t('course.sync.syncSuccess'))
    } else {
      message.error(t('course.sync.syncFail'))
    }
  } catch {
  } finally {
    loading.value = false
  }
}

const semesterList = ref<SemesterSimpleRespVO[]>([])
const getSemesterSimpleList = async () => {
  semesterList.value = await SemesterApi.getSemesterSimpleList()
}

const accountLoading = ref(false)
const accountList = ref<CourseSignStudentLogListRespVO[]>([])
const accountTitle = ref('')
const dialogVisible = ref(false)
const handleViewTwice = async (ids: number[], type: string) => {
  accountTitle.value = type
  accountList.value = []
  accountLoading.value = true
  dialogVisible.value = true
  accountList.value = await CourseApi.getAccountInfo(ids)
  accountLoading.value = false
}

/** 初始化 **/
onMounted(() => {
  getList()
  getSemesterSimpleList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
